import FileModal from "../../FileModal/index.vue"
import { reactive, ref } from "vue"
import { FileItemType } from "../type"
import type { FormDataType } from "../../FileModal/type"
import { useStore } from "@/store"

function useModal(expandTree: () => void) {
  const store = useStore()
  const filterNode: any = (value: string, data: FileItemType) => {
    if (!value) return true
    return data.name.indexOf(value) !== -1
  }

  // 文件弹出框相关
  type FileModalType = InstanceType<typeof FileModal> & {
    formData: FormDataType
  }

  const fileModalProp = reactive({
    isDir: false,
    flag: false,
    parentId: null as null | number,
    handle: "add" as FileModalType["handle"],
  })

  const fileModalRef = ref<FileModalType>()
  const showModal = (
    isDir: boolean,
    parentId: null | number,
    handle: FileModalType["handle"] = "add",
    data?: FileItemType
  ) => {
    fileModalProp.flag = true
    fileModalProp.isDir = isDir
    fileModalProp.parentId = parentId
    fileModalProp.handle = handle
    if (handle === "update") {
      const formData = fileModalRef.value?.formData
      console.log(fileModalRef.value)
      formData.fileId = data?.id
      formData.name = data?.name
      formData.editable = data?.editable
    }
  }

  const beforeUpdateFile = async (
    parentId: number,
    handle: FileModalType["handle"]
  ) => {
    await store.dispatch("fileTree/getFile")
    if (handle === "add") {
      // 若为添加操作则展开添加的文件夹
      store.commit(
        "fileTree/changeTreeExpandedArr",
        store.state.fileTree.treeExpandedArr.concat(parentId + "")
      )
    }
    expandTree()
  }
  return {
    fileModalProp,
    filterNode,
    fileModalRef,
    showModal,
    beforeUpdateFile,
  }
}

export default useModal
